/*
 * Copyright (C) 2010 Leandro Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.mjl.factory;

import java.util.*;

import org.apache.log4j.*;
import org.apache.log4j.LogManager;
import org.apache.log4j.spi.*;

import com.google.code.mjl.*;
import com.google.code.mjl.impl.*;
import com.google.common.collect.*;

// be carefull with LoggingEvent in custom appenders (lazily initialized
// ThrowableInformation won't be correct if it's used in asynchronous mode)
public class Log4jLogAdapterFactory implements LogAdapterFactory {

	private static final EnumMap<Log.Level, Level> LEVEL_MAPPING = Maps.newEnumMap(Log.Level.class);

	static {
		LEVEL_MAPPING.put(Log.Level.TRACE, Level.TRACE);
		LEVEL_MAPPING.put(Log.Level.DEBUG, Level.DEBUG);
		LEVEL_MAPPING.put(Log.Level.INFO, Level.INFO);
		LEVEL_MAPPING.put(Log.Level.WARN, Level.WARN);
		LEVEL_MAPPING.put(Log.Level.ERROR, Level.ERROR);
		LEVEL_MAPPING.put(Log.Level.FATAL, Level.FATAL);
	}

	public LogAdapter create(String categoryName) {
		final Logger logger = Logger.getLogger(categoryName);
		return new LogAdapter() {
			public boolean isEnabled(Log.Level level) {
				return logger.isEnabledFor(LEVEL_MAPPING.get(level));
			}

			public void log(LogEvent event) {
				LoggingEvent loggingEvent = new Log4jLoggingEvent(event, logger);
				logger.callAppenders(loggingEvent);
			}
		};
	}

	public void shutdown() {
		LogManager.shutdown();
	}

	private static class Log4jLoggingEvent extends LoggingEvent {
		private static final long serialVersionUID = 6830717674786993106L;
		private final String threadName;

		Log4jLoggingEvent(LogEvent logEvent, Category category) {
			super("", category, logEvent.time(), LEVEL_MAPPING.get(logEvent.level()), logEvent.message(), logEvent.throwable());
			threadName = logEvent.threadName();
		}

		@Override
		public String getThreadName() {
			return threadName;
		}
	}
}
